import sys
import os
import time
import logging
from threading import Thread

import paramiko


logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s line:%(lineno)d %(levelname)s:%(message)s',
                    datefmt='%H:%M:%S',
                    )
                
class Ssh():
    def __init__(self, ip, port=22, username="root", password="123"):
        self.ssh = None
        transport = paramiko.Transport((ip, port))
        transport.connect(username=username, password=password)
        self.ssh = paramiko.SSHClient()
        self.ssh._transport = transport
        
        # mkdir() remove() rename() stat() listdir() 
        self.sftp = paramiko.SFTPClient.from_transport(transport)
        self.channel = self.ssh.invoke_shell()
        
        #self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # self.client.connect(hostname=ip, port=port, username=username, password=password)
        
    def run(self, cmd, timeout=None):
        logging.info(cmd)
        stdin, stdout, stderr = self.ssh.exec_command(cmd, timeout=timeout)
        channel = stdout.channel
        ret = channel.recv_exit_status()
        text = stdout.read().decode('utf-8') + stderr.read().decode('utf-8')
        if text.strip():
            logging.info(text)
        return ret == 0, text

    def run2(self, cmd, timeout=None):
        logging.info(cmd)
        self.channel.sendall(cmd + "\n")

    def recv(self, sleep=0.1, size=4096):
        time.sleep(sleep)
        return self.channel.recv(size).decode()

    def upload(self, local_path, remote_path):
        if os.path.isfile(local_path):
            self.run("mkdir -p '%s'" % os.path.dirname(remote_path))
            return self.sftp.put(local_path, remote_path)
        if not os.path.isdir(local_path):
            raise Exception("%s is not exists" % local_path)
        self.run("mkdir -p '%s'" % remote_path)
        for name in os.listdir(local_path):
            src = os.path.join(local_path, name)
            des = "%s/%s" % (remote_path, name)
            if os.path.isdir(src):
                if not self.upload(src, des):
                    return False
            else:
                if not self.sftp.put(src, des):
                    return False
        return True

    def download(self, local_path, remote_path):
        self.sftp.get(remote_path, local_path)

    def __del__(self):
        if self.ssh:
            self.ssh.close()
            #self.sftp.close()
 
   
if __name__ == "__main__":
    ssh = Ssh("7.222.97.140", 22, "root", "Huawei@23")
    ssh.run("pwd")
    ssh.recv_flag = False

 